package com.example.exception;

import com.example.pojo.RestfulApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * @author jie
 * @date 2021/11/25 -18:17
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public RestfulApiResponse globalExceptionHandle(Exception ex) {
        log.error("执行请求的过程中发生了未经处理的异常：" + ex.getMessage(), ex);
        return RestfulApiResponse.error(ex.getMessage(), "详情请查看日志");
    }

    private static String getStackTrace(Throwable e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        e.printStackTrace(pw);
        pw.flush();
        sw.flush();
        return sw.toString();
    }
}
